﻿using DimensionsHelper.Common.Contracts.Table;

namespace DimensionsHelper.Services.CsvReader;

public class CsvTableRecognizer : ITableRecognizer
{
    private readonly string _tableBaseFeature;
    private readonly string _tableEndFeature;

    private readonly string _tableTitleFeature;

    private CsvTableRecognizer(string tableTitleFeature, string tableEndFeature, string tableBaseFeature)
    {
        _tableTitleFeature = tableTitleFeature;
        _tableEndFeature = tableEndFeature;
        _tableBaseFeature = tableBaseFeature;
    }

    public bool IsTableBaseLine(ILine line)
    {
        return !string.IsNullOrEmpty(_tableBaseFeature) && line.NotEmptyCellCount > 1 &&
               line[0].Text.StartsWith(_tableBaseFeature);
    }

    public bool IsTableEndLine(ILine line)
    {
        return line is { IsEmpty: false, Count: > 0 } && line[0].Text.StartsWith(_tableEndFeature);
    }

    public bool IsTableStartLine(ILine line)
    {
        if (line is { IsEmpty: true, NextLine: not null } && line.NextLine.TestLineType(LineType.HeaderSpec))
        {
            return true;
        }

        return line.PreviousLine is null || (
            line.IsEmpty && line.PreviousLine.IsEmpty && line.Count == line.PreviousLine.Count);
    }

    public bool IsTableTitleCell(ICell cell)
    {
        return cell.Text.StartsWith(_tableTitleFeature);
    }

    public static ITableRecognizer Create(string tableTitleFeature, string tableEndFeature, string tableBaseFeature)
    {
        return new CsvTableRecognizer(tableTitleFeature, tableEndFeature, tableBaseFeature);
    }
}